﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using TV_Organizer.FileScanner;
using TV_Organizer.Properties;
using MahApps.Metro.Controls;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Timers;

namespace TV_Organizer
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        public MainWindow()
        {
            this.Left = Settings.Default.MainWindowLocation.X;
            this.Top = Settings.Default.MainWindowLocation.Y;

            if (Settings.Default.MainWindowMaximized)
                this.WindowState = System.Windows.WindowState.Maximized;

            var l_screenBounds = System.Windows.Forms.SystemInformation.VirtualScreen;
            if (this.Left > l_screenBounds.Right - 50)
                this.Left = l_screenBounds.Right - 50;
            if (this.Top > l_screenBounds.Bottom - 50)
                this.Top = l_screenBounds.Bottom - 50;

            InitializeComponent();
        }

        #region props
        
        public static readonly DependencyProperty ProgressBarMinimumProperty = DependencyProperty.Register("ProgressBarMinimum", typeof(int), typeof(MainWindow), new UIPropertyMetadata(0));
        public int ProgressBarMinimum
        {
            get { return this.SafelyGetValue<int>(ProgressBarMinimumProperty); }
            set { this.SafelySetValue(ProgressBarMinimumProperty, value); }
        }

        public static readonly DependencyProperty ProgressBarValueProperty = DependencyProperty.Register("ProgressBarValue", typeof(int), typeof(MainWindow), new UIPropertyMetadata(0));
        public int ProgressBarValue
        {
            get { return this.SafelyGetValue<int>(ProgressBarValueProperty); }
            set { this.SafelySetValue(ProgressBarValueProperty, value); }
        }

        public static readonly DependencyProperty ProgressBarMaximumProperty = DependencyProperty.Register("ProgressBarMaximum", typeof(int), typeof(MainWindow), new UIPropertyMetadata(100));
        public int ProgressBarMaximum
        {
            get { return this.SafelyGetValue<int>(ProgressBarMaximumProperty); }
            set { this.SafelySetValue(ProgressBarMaximumProperty, value); }
        }

        public static readonly DependencyProperty BusyHeaderProperty = DependencyProperty.Register("BusyHeader", typeof(string), typeof(MainWindow), new UIPropertyMetadata("Please wait..."));
        public string BusyHeader
        {
            get { return this.SafelyGetValue<string>(BusyHeaderProperty); }
            set { this.SafelySetValue(BusyHeaderProperty, value); }
        }

        public static readonly DependencyProperty BusyMessageProperty = DependencyProperty.Register("BusyMessage", typeof(string), typeof(MainWindow), new UIPropertyMetadata("Loading"));
        public string BusyMessage
        {
            get { return this.SafelyGetValue<string>(BusyMessageProperty); }
            set { this.SafelySetValue(BusyMessageProperty, value); }
        }

        public static readonly DependencyProperty ProgressBarVisibilityProperty = DependencyProperty.Register("ProgressBarVisibility", typeof(Visibility), typeof(MainWindow), new UIPropertyMetadata(Visibility.Visible));
        public Visibility ProgressBarVisibility
        {
            get { return (Visibility)GetValue(ProgressBarVisibilityProperty); }
            set { SetValue(ProgressBarVisibilityProperty, value); }
        }

        #endregion

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            Settings.Default.MainWindowLocation = new Point(this.Left, this.Top);

            if (this.WindowState == System.Windows.WindowState.Maximized)
                Settings.Default.MainWindowMaximized = true;

            base.OnClosing(e);
        }

        private void WorkingBorder_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        protected override void OnStateChanged(EventArgs e)
        {
            if (WindowState == WindowState.Minimized)
                this.Hide();

            base.OnStateChanged(e);
        }

        //public void WriteToStatusBar(string text, params object[] stringFormatArgs)
        //{
        //    this.WriteToStatusBar(string.Format(text, stringFormatArgs));
        //}

        //public void WriteToStatusBar(string text)
        //{
        //    Application.Current.Dispatcher.BeginInvoke(new System.Action<string>((str) =>
        //    {
        //        this.StatusTextBlock.Text = str;
        //    }), new object[] { text });
        //}

        private const string _openSBName = "OpenSB";
        private const string _closeSBName = "CloseSB";
        private static readonly TimeSpan _notificationDuration = TimeSpan.FromSeconds(3.0);
        private static Timer _notificationTimer;

        public void Notify(string message, params object[] stringFormatArgs)
        {
            if (!Application.Current.Dispatcher.CheckAccess())
            {
                Application.Current.Dispatcher.Invoke(new System.Action(() => this.Notify(message, stringFormatArgs)));
                return;
            }

            var openSB = this.NotificationGrid.FindResource(_openSBName) as Storyboard;

            this.NotificationTextBlock.Text = string.Format(message, stringFormatArgs);
            openSB.Begin();

            if (_notificationTimer == null)
            {
                _notificationTimer = new Timer
                {
                    Interval = _notificationDuration.TotalMilliseconds,
                    AutoReset = false,
                };
                _notificationTimer.Elapsed += new ElapsedEventHandler(OnNotificationTimer_Elapsed);
            }
            _notificationTimer.Stop();
            _notificationTimer.Start();
        }

        void OnNotificationTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Application.Current.Dispatcher.BeginInvoke(new System.Action(() =>
            {
                var closeSB = this.NotificationGrid.FindResource(_closeSBName) as Storyboard;
                closeSB.Begin();
            }));
        }

        #region Busy indicator

        public void DisplayBusyIndicator(string header, string message, Visibility progressBarVisibility = System.Windows.Visibility.Visible)
        {
            if(!Application.Current.Dispatcher.CheckAccess())
            {
                Application.Current.Dispatcher.Invoke(new System.Action(() => this.DisplayBusyIndicator(header, message, progressBarVisibility)));
                return;
            }

            this.ProgressBarVisibility = progressBarVisibility;
            this.BusyIndicator.IsBusy = true;
            this.BusyHeader = header;
            this.BusyMessage = message;
        }

        public void HideBusyIndicator()
        {
            if (!Application.Current.Dispatcher.CheckAccess())
            {
                Application.Current.Dispatcher.Invoke(new System.Action(() => this.HideBusyIndicator()));
                return;
            }

            this.BusyIndicator.IsBusy = false;
        }

        #endregion
    }
}
